import __config from './config'
import es6 from '../assets/plugins/es6-promise'
import WxServe from './WxService'
import Store from './store'
let WxServeApi = new WxServe()
let Storage = new Store()

class ServiceBase {
  constructor() {
    Object.assign(this, {
      $$basePath: __config.basePath
    })

  }

  __init() {
    const that = this

    // 方法名后缀字符串
    that.suffix = 'Request'

    // 发起请求所支持的方法
    that.instanceSource = {
      method: [
        'OPTIONS',
        'GET',
        'HEAD',
        'POST',
        'PUT',
        'DELETE',
        'TRACE',
        'CONNECT',
      ]
    }

    // 遍历对象构造方法，方法名以小写字母+后缀名
    for (let key in that.instanceSource) {
      that.instanceSource[key].forEach(function (method) {
        that[method.toLowerCase() + that.suffix] = function () {
          return that.__getPromise(es6.Promise, that.__getResolver(that.__defaultRequest, [method, ...Array.from(arguments)], that))
        }
      })
    }
  }

  /**
   * __getPromise
   */
  __getPromise(Promise, resolver) {
    if (Promise) return new Promise(resolver)
    throw new Error('Promise library is not supported')
  }

  /**
   * __getResolver
   */
  __getResolver(method, args, context) {
    return function (resolve, reject) {
      method.apply(context, args)(resolve, reject)
    }
  }

  /**
   * 以wx.request作为底层方法
   * @param {String} method 请求方法
   * @param {String} url    接口地址
   * @param {Object} params 请求参数
   */
  http(params) {
    params['url'] = params.url ? params.url : ''
    params['method'] = params.method ? params.method : 'POST'
    params['loading'] = params.loading ? params.loading : true
    params['params'] = params.params ? params.params : {}
    const $$header = this.setHeaders()
    const $$url = `${this.$$basePath}` + params.url
    if (params.loading) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 10000,
        mask: !0,
      })
    }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: $$url,
        method: params.method,
        data: params.params,
        header: $$header,
        success: res => {
          wx.hideToast()
          if (res.data.errno === 0) {
            resolve(res.data.data)
          } else if (res.data.errno === 401) {
            Storage.remove('token')
            wx.showModal({
              title: '温馨提示',
              content: '请先登录',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  WxServeApi.navigateTo(`/pages/login/index`)
                }
              }
            })
            reject(res.data)
          } else {
            reject(res.data)
            wx.showToast({
              title: res.data.msg ? res.data.msg : res.data.errmsg,
              icon: 'warning'
            })
            setTimeout(() => {
              wx.hideToast()
            }, 1200)
          }

        },
        fail: res => {
          wx.hideToast()
          wx.showToast({
            title: res.data.msg ? res.data.msg : res.data.errmsg,
            icon: 'warning'
          })
          setTimeout(() => {
            wx.hideToast()
          }, 1200)

          reject(res.data)
        }
      })
    })


  }
  upload(params) {
    const $$header = this.setHeaders()
    const $$url = `${this.$$basePath}` + params.url
    if (params.loading) {
      wx.showToast({
        title: '正在上传...',
        icon: 'loading',
        mask: true,
        duration: 10000
      })
    }
    return new Promise(function (resolve, reject) {
      wx.uploadFile({
        url: $$url, //仅为示例，非真实的接口地址
        filePath: params.params,
        name: params.type ? params.type : 'file',
        header: $$header,
        formData: {
          'content-type': 'multipart/form-data'
        },
        success(res) {
          wx.hideToast()
          let result = JSON.parse(res.data)
          resolve(result)
        },
        fail(err) {
          wx.hideToast()
          let result = JSON.parse(res.data)
          reject(result)
        }
      })
    })
  }
  /**
   * 设置请求的 header , header 中不能设置 Referer
   */
  setHeaders() {
    return {
      'Accept': 'application/json',
      'Content-type': 'application/json',
      'Authorization': 'Bearer ' + Storage.get('token'),
      'X-Nideshop-Token': Storage.get('token')
    }
  }
}

export default ServiceBase